package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetMealMapper;
import com.sky.mapper.ShopCartMapper;
import com.sky.service.ShopCartService;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class ShopCartServiceImpl implements ShopCartService {
    @Autowired
    private ShopCartMapper shopCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetMealMapper setMealMapper;

    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, shoppingCart);

        // 赋值用户id
        shoppingCart.setUserId(BaseContext.getCurrentId());

        // 判断是否存在
        List<ShoppingCart> shoppingCartList = shopCartMapper.selectShoppingList(shoppingCart);
        if(shoppingCartList != null && shoppingCartList.size() == 1) {
            // 购物车存在，修改数 +1
            ShoppingCart shoppingCartInfo = shoppingCartList.get(0);
            shoppingCartInfo.setNumber(shoppingCartInfo.getNumber() + 1);

            shopCartMapper.updateCount(shoppingCartInfo);
        }else {
            // 判断是否是套餐还是单菜
            if(shoppingCart.getDishId() != null) {
                // 此时是菜品
                Long dishId = shoppingCart.getDishId();
                DishVO dishVO = dishMapper.selectById(dishId);
                shoppingCart.setName(dishVO.getName());
                shoppingCart.setImage(dishVO.getImage());
                shoppingCart.setAmount(dishVO.getPrice());
            }else {
                // 此时为套餐
                Long setMealId = shoppingCart.getSetmealId();
                SetmealVO setmealVO = setMealMapper.selectById(setMealId);
                shoppingCart.setName(setmealVO.getName());
                shoppingCart.setImage(setmealVO.getImage());
                shoppingCart.setAmount(setmealVO.getPrice());
            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);

            // 调用新增
            shopCartMapper.insertShopping(shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> getShoppingCartList() {
        List<ShoppingCart> shoppingCartList = shopCartMapper.selectShoppingList(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());

        return shoppingCartList;
    }
}
